package com.nulldev.util.web.dns.server.server.engine;

import java.util.regex.Pattern;

import com.nulldev.util.logging.Logger;
import com.nulldev.util.logging.LoggerFactory;
import com.nulldev.util.web.dns.server.server.DNSPayload;
import com.nulldev.util.web.dns.server.server.resolver.DNSResolver;

public class AddressRegexResolverRule implements ResolverRule {
	private final Logger logger = LoggerFactory.getLogger(AddressRegexResolverRule.class);

    private String regex;
    private Pattern pattern;
    private DNSResolver resolver;

    /**
     * Creates a new resolver rule with the supplied regular expression and resolver.
     * @param regex Regular expression string
     * @param resolver Resolver to be used in question resolution
     */
    public AddressRegexResolverRule(String regex, DNSResolver resolver) {
        this.resolver = resolver;
        this.regex = regex;
        this.pattern = Pattern.compile(regex);
    }

    /**
     * Compares socket address to regular expression to determine whether or not this is a valid resolver rule.
     * @param payload
     * @return
     */
    @Override
    public boolean isValid(DNSPayload payload) {
        logger.debug("Checking {} against pattern {}", payload.getRemoteAddress(), regex);
        return pattern.matcher(payload.getRemoteAddress().toString()).matches();
    }

    /**
     * Get the regular expression used by this rule.
     * @return Regular expressions string
     */
    public String getRegex() {
        return regex;
    }

    /**
     * Set the regular expression used by this rule.
     * @param regex Regular expression string
     */
    public void setRegex(String regex) {
        this.regex = regex;
        this.pattern = Pattern.compile(regex);
    }

    /**
     * Get the question resolver used by this rule.
     * @return Question resolver
     */
    @Override
    public DNSResolver getResolver() {
        return resolver;
    }

    /**
     * Set the question resolver used by thi rule.
     * @param resolver Question resolver
     */
    public void setResolver(DNSResolver resolver) {
        this.resolver = resolver;
    }
}
